<?php
/**
 * Permission Service
 * User: zng
 * Date: 2019/11/4
 * Time: 14:34
 */
namespace app\admin\service\questions;

use app\admin\model\questions\QuestionCategory as QuestionCategoryModels;

Class QuestionCategory {

    /**
     * 首页列表
     * @param array $get 筛选条件
     * @return \think\Paginator
     */
    public function indexPaginate( array $get=[] )
    {
        $map = [];

        if ( get($get, 'title') ) {
            $map[] = ['title', 'LIKE', '%'.$get['title'].'%'];
        }
        $pageSize = get($get,'pageSize')>0?$get['pageSize']:20;

        return QuestionCategoryModels::with(['parents'=>function($query){
                $query->with(['parents']);
            }])
            ->where($map)
            ->order('id', 'desc')
            ->paginate($pageSize);
    }

    /**
     * 新增题目分类信息
     * @param array $data 数据包
     * @return boolean|integer
     */
    public function create(array $data)
    {
        $data['level'] = $data['pid']>0?3:2;
        $data['pid'] = $data['pid']?:2;
        $question = QuestionCategoryModels::create($data, ['title','pid','level']);
        return $question->isEmpty()?false:$question->id;
    }

    /**
     * 批量删除
     * @param mixed $data
     * @return boolean
     */
    public function destory( $data )
    {
        return QuestionCategoryModels::destroy(function($query)use($data){
            $where = ['id', '=', $data];
            if ( is_array($data) ) {
                $where = ['id', 'in', $data];
            }
            $query->where([
                $where
            ]);
        });
    }

    /**
     * 题目分类管理编辑
     * @param QuestionCategoryModels $model
     * @param array $data
     * @return boolean
     */
    public function save(QuestionCategoryModels $model, array $data)
    {
        $model->title = $data['title'];
        $model->pid = $data['pid']?:2;
        $model->level = $data['pid']>0?3:2;
        return $model->save();
    }

    /**
     * 获取二级分类
     * @return array
     */
    public function getSecond()
    {
        return QuestionCategoryModels::field('id,title')->where('level', 2)->select()->toArray();
    }

    /**
     * 获取分类列表
     * @return mixed
     */
    public function getLists()
    {
        return QuestionCategoryModels::with(['child'=>function($query){
            $query->with(['child']);
        }])->where('level', 1)->select();
    }

}